package cinema.Controller;

import cinema.Dao.UserDAO;
import cinema.Entity.User;
import sun.misc.BASE64Encoder;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@SessionScoped
@Named
@SuppressWarnings("serial")
public class LoginBean implements Serializable {

    @Inject
    private UserDAO userDAO;

    private User activeUser;

    public boolean logIn(String uname, String password) {
        MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance("SHA");
        }
        catch(Exception e){}
        try
        {
            md.update(password.getBytes("UTF-8"));
        }
        catch(Exception e){}

        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);

        User user = userDAO.validateUser(uname, hash);
        if (user != null) {
            activeUser = new User(user);
            return true;
        }
        return false;
    }

    public void checkLogin() {
        if (activeUser == null) {
            ((ConfigurableNavigationHandler) FacesContext.getCurrentInstance().getApplication().getNavigationHandler()).performNavigation("adminLogin");
        }
    }

    public String logOut() {
        activeUser = null;
        return "index?faces-redirect=true";
    }

    public User getActiveUser() {
        return activeUser;
    }

}
